package com.wjbgn.bsolver.message.websocket.config;

import com.wjbgn.bsolver.message.websocket.WebSocketServer;
import com.wjbgn.stater.util.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.List;

/**
 * 初始化皮配置
 *
 * @author weirx
 * @date 2022/03/23 11:39
 **/
@Slf4j
@Configuration
public class WebSocketInitConfig implements ApplicationRunner {

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${spring.application.name}")
    private String serviceId;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取nacos上注册的所有xxx实例
     *
     * @return
     */
    private void getServiceInstance() {
        //这里的xxx即为nacos控制面板上的服务名
        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances(serviceId);
        if (serviceInstanceList.size() == 1) {
            // 清除websocket的人数统计
            Boolean aBoolean = redisUtil.deleteObject(WebSocketServer.USER_COUNT);
            if (!aBoolean) {
                log.info("[WebSocketInitConfig.getServiceInstance]清除websocket登陆人数失败");
            }
        }
    }

    @Override
    public void run(ApplicationArguments args) {
        this.getServiceInstance();
    }
}
